package com.fagp.mew.cms.annotation;

import com.alibaba.fastjson.JSON;
import com.fagp.mew.cms.messages.PageResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author tansonglin
 * @date 2021/9/24 11:32
 */
@Aspect
@Component
@Slf4j
public class ValidConfigPasAspect {
    @Value(value = "${config-valid.password}")
    private String password;

    @Pointcut("@annotation(com.fagp.mew.cms.annotation.ValidConfigPass)")
    public void annotationPointcut() {

    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) {

    }

    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String configPassword = request.getParameter("configPassword");
        if(null == configPassword){
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String mes = "请传入安全密码";
            log.error(mes);
            returnJson(response, JSON.toJSONString(new PageResponse(mes)));
            return null;
        }
        if(!password.equals(configPassword)){
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String mes = "安全密码输入错误";
            log.error(mes);
            returnJson(response, JSON.toJSONString(new PageResponse(mes)));
            return null;
        }
/*
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] params = methodSignature.getParameterNames();// 获取参数名称
        Object[] args = joinPoint.getArgs();// 获取参数值
        if (null == params || params.length == 0){
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String mes = "未传入参数";
            log.error(mes);
            returnJson(response, JSON.toJSONString(new PageResponse(mes)));
            return null;
        }
        boolean hasCP = false;
        int index = 0;
        for (int i = 0; i < params.length; i++) {
            if ("configPassword".equals(params[i])) {
                hasCP = true;
                index = i;
                break;
            }
        }
        if (!hasCP){
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String mes = "未传入参数修改密码";
            log.error(mes);
            returnJson(response, JSON.toJSONString(new PageResponse(mes)));
            return null;
        }
        if(!password.equals(String.valueOf(args[index]))){
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String mes = "密码输入错误";
            log.error(mes);
            returnJson(response, JSON.toJSONString(new PageResponse(mes)));
            return null;
        }*/
        return joinPoint.proceed();
    }

    /**
     * 在切入点return内容之后切入内容（可以用来对处理返回值做一些加工处理）
     * @param joinPoint
     */
    @AfterReturning("annotationPointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
    }


    public static void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.info(e.getMessage());
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
